package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @ClassName RedisIdWorker
 * @Description TODO
 * @Author kiku
 * @Date 2025/2/10 11:53
 * @Version 1.0
 */
@Component
public class RedisIdWorker {
    //起始时间戳
    private static final long BEGIN_TIMESTAMP = 1640995200L;
    //序列号的位数
    private static final int COUNT_BITS=32;
    @Autowired
    private StringRedisTemplate redisTemplate;

    //实现全局唯一id
    public long nextId(String keyPrefix) {
        //0-时间戳-序列号
        LocalDateTime now = LocalDateTime.now();
        long current = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = current - BEGIN_TIMESTAMP;
        //生成序列号
        //获取日期精确到天
        String date = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        long count = redisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
        return timestamp<<COUNT_BITS|count;
    }

    public static void main(String[] args) {
        LocalDateTime dateTime = LocalDateTime.of(2022, 1, 1, 0, 0, 0);
        long second = dateTime.toEpochSecond(ZoneOffset.UTC);
        System.out.println(second);
    }
}
